﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.IO;
using Microsoft.TeamFoundation.Build.Client;

namespace BDV.TfsCustomActivities.BuildTasks
{
    /// <summary>
    /// Do a checkout on files that mathes the provided pattern
    /// Checkout de fichiers sur base d'un masque de recherche. Tous les fichiers dont le nom correspond au masque seront checkoutés et retournés dans la variable <see cref="AssemblyInfoFilesFound"/>
    /// </summary>
    [BuildActivity(HostEnvironmentOption.All)]
    public sealed class CheckOutFilesBySearchMask : CodeActivity
    {
        /// <summary>
        /// Pattern used to find files
        /// Masque décrivant le nom de fichier à rechercher dans l'arborescence. 
        /// </summary>
        [RequiredArgument]
        public InArgument<string> AssemblyInfoFileMask { get; set; }

        /// <summary>
        /// Workspace concerned
        /// </summary>
        [RequiredArgument]
        public InArgument<Workspace> WorkSpace { get; set; }

        /// <summary>
        /// OUT - List of checkouted files
        /// </summary>
        [RequiredArgument]
        public OutArgument<List<string>> FilesFound { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the Text input argument
            string assemblyInfoFileMask = context.GetValue(this.AssemblyInfoFileMask);
            Workspace wkSpace = context.GetValue(this.WorkSpace);

            var result = new List<string>();

            if (!string.IsNullOrEmpty(assemblyInfoFileMask))
                foreach (var folder in wkSpace.Folders.Where(f => !f.IsCloaked))
                    foreach (var file in Directory.GetFiles(folder.LocalItem, assemblyInfoFileMask, SearchOption.AllDirectories))
                    {
                        wkSpace.PendEdit(file);
                        result.Add(file);
                    }

            this.FilesFound.Set(context, result);
        }
    }
}
